const Router = require('koa-router');
const users = require('../models/users');
const router = new Router();
router.prefix('/api/users');

// 登录路由
router.post('/login', async (ctx) => {
  const { loginName, password } = ctx.request.body;
  const userResult = await users.validateUser(loginName, password);

  if (userResult.status === 0) {
    ctx.session = {
      user: {
        loginName: userResult.user.login_name,
        rootPath: `/home/${userResult.user.login_name}`,
        currentPath: `/home/${userResult.user.login_name}` // 初始化为根目录
      }
    };
    ctx.body = { status: 0, msg: '登录成功', currentPath: ctx.session.user.currentPath };
  } else {
    ctx.status = 401;
    ctx.body = { status: 12, msg: '登录失败' };
  }
});

// 注册路由
router.post('/register', async (ctx) => {
  const { login_name, password } = ctx.request.body;
  const registerResult = await users.registerUser(login_name, password);

  if (registerResult.status === 0) {
    ctx.body = { status: 0, msg: '注册成功', userId: registerResult.userId };
  } else {
    ctx.status = 400;
    ctx.body = { status: registerResult.status, msg: registerResult.msg };
  }
});

// 退出登录路由
router.post('/logout', async (ctx) => {
  ctx.session = null;
  ctx.body = { status: 0, msg: '已退出登录' };
});

module.exports = router;


